import {Component, HostListener, OnInit} from '@angular/core';
import {DatePipe} from '@angular/common';
import {EmitService} from '../../../providers/emit.service';
import {HttpService} from '../../../providers/http.service';
import {NzMessageService} from 'ng-zorro-antd/message';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {debounceTime, distinctUntilChanged, first, map, switchMap} from 'rxjs/internal/operators';
import {observable} from 'rxjs/index';
import {Xutils} from '../../../utils/xutils';

@Component({
  selector: 'app-sysuser',
  templateUrl: './sysuser.component.html',
  styleUrls: ['./sysuser.component.css'],

})
export class SysUserComponent implements OnInit {

  autoHeight: number = 480;
  tab = {
    name: '用户管理',
    url: '/page/system/user',
    closeIcon: true
  };

  loading = false;
  _page = {rows: [], total: 0};
  _cnd: any = {pageNum: 1, pageSize: 10};
  createTimes;
  _ngTree = [];
  roles = [];

  constructor(public emitService: EmitService,
              private httpService: HttpService,
              private message: NzMessageService,
              private fb: FormBuilder,
              private datePipe: DatePipe) {
  }

  ngOnInit() {

    //初始化表单
    this.buildForm();

    // 通知父组件
    this.emitService.tabsEmit.emit(this.tab);

    // 列表查询
    this.search(true);

    this.httpService.post('system/dept/treeList', this._cnd, (result) => {
      if (result.code !== 0) {
        this.message.error('操作失败：' + result.msg);
        return;
      }
      this._ngTree = result.data;
    }, (errorResult) => {
      this.message.error(errorResult.msg);
    });


  }


  search(reset: boolean = false): void {
    if (reset) {
      let currentPageNum = this._cnd.pageNum;
      let currentPageSize = this._cnd.pageSize;
      this.createTimes = null;
      this._cnd = {pageNum: 1, pageSize: currentPageSize};
    }

    this._cnd.params = {};
    this.checkedIdMap = {};
    if (this.createTimes != null && this.createTimes.length > 0) {
      this._cnd.params = {
        beginCreateTime: this.datePipe.transform(this.createTimes[0], 'yyyy-MM-dd') + ' 00:00:00',
        endCreateTime: this.datePipe.transform(this.createTimes[1], 'yyyy-MM-dd') + ' 23:59:59',
      };
    }


    this.loading = true;
    this.httpService.post('system/user/list', this._cnd, (result) => {
      this.loading = false;
      if (result.code !== 0) {
        this.message.error('操作失败：' + result.msg);
        return;
      }
      this._page = result.data;
    }, (errorResult) => {
      this.loading = false;
      this.message.error(errorResult.msg);
    });
  }

  // checkbox
  isAllChecked = false;
  checkedIdMap: { [key: string]: boolean } = {};
  isEditBtn = false;
  isDeleteBtn = false;

  checkedAll(isChecked: boolean) {
    this._page.rows.forEach(item => (this.checkedIdMap[item.userId] = isChecked));
    this.checkedChange();
  }

  checkedChange() {
    this.isAllChecked = this._page.rows.every(item => this.checkedIdMap[item.userId]);
    this.isDeleteBtn = this._page.rows.some(item => this.checkedIdMap[item.userId]);
    this.isEditBtn = false;
    let rows = this._page.rows;
    let count = 0;
    for (let i = 0; i < rows.length; i++) {
      if (this.checkedIdMap[rows[i].userId]) {
        count++;
      }
    }
    if (count == 1) {
      this.isEditBtn = true;
    }
  }

  // form crud
  modalWidth = 800;
  modalTitle = '用户信息信息';
  validateForm: FormGroup;
  isVisible = false;
  isOkLoading = false;

  buildForm() {
    this.validateForm = this.fb.group({
      userId: [null, null],
      deptId: [null, [Validators.required]],
      loginName: [null, null],
      userName: [null, [Validators.required], this.asyncUniqueValidate('userName')],
      userType: [null, null],
      email: [null, [Validators.required, Validators.email], this.asyncUniqueValidate('email')],
      phonenumber: [null, [Validators.required], this.asyncUniqueValidate('phonenumber')],
      sex: [null, null],
      avatar: [null, null],
      status: [null, null],
      roleIds: [null, null],
    });
  }

  saveOrUpdate(): void {
    if (this.validateForm.invalid) {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
      return;
    }
    this.isOkLoading = true;
    //获取角色id
    if (this.roles != null && this.roles.length > 0) {
      let roleIds = [];
      for (let r of this.roles) {
        if (r.userChecked) {
          roleIds.push(r.roleId);
        }
      }
      if (roleIds.length > 0) {
        this.validateForm.value.roleIds = roleIds.join(',');
      }
    }

    let url = 'system/user/add';
    let userId = this.validateForm.value.userId;
    if (userId && userId > 0) {
      url = 'system/user/edit';
    }
    this.httpService.post(url, this.validateForm.value, (result) => {
      this.isOkLoading = false;
      if (result.code !== 0) {
        this.message.error('操作失败：' + result.msg);
        return;
      }
      this.isVisible = false;
      this.message.success('操作成功');
      this.search();
    }, (errorResult) => {
      this.isOkLoading = false;
      this.isVisible = false;
      this.message.error(errorResult.msg);
    });
  }

  deleteOne(id) {
    this.httpService.post('system/user/delete', {ids: id}, (result) => {
      if (result.code !== 0) {
        this.message.error('操作失败：' + result.msg);
        return;
      }
      this.message.success('删除成功');
      this.search();
    }, (errorResult) => {
      this.message.error(errorResult.msg);
    });
  }

  deleteSome() {
    let ids = this.getCheckedIds();
    this.deleteOne(ids);
  }

  editInfo(id) {
    this.searchRoles(id);
    this.httpService.post('system/user/getById', {userId: id}, (result) => {
      if (result.code !== 0) {
        this.message.error('操作失败：' + result.msg);
        return;
      }
      this.openOrCloseModal(true);
      this.validateForm.patchValue(result.data);
    }, (errorResult) => {
      this.message.error(errorResult.msg);
    });
  }

  // 列表上面的编辑按钮
  editInfoTop() {
    let id = this.getCheckedIds();
    this.editInfo(id);
  }

  addInfo() {
    this.searchRoles(null);
    this.openOrCloseModal(true);
  }

  openOrCloseModal(isVisible): void {
    this.autoHeight = document.documentElement.clientHeight - 250;
    this.isVisible = isVisible;
    this.isOkLoading = false;
    this.validateForm.reset();
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsPristine();
      this.validateForm.controls[key].updateValueAndValidity();
    }
  }

  getCheckedIds() {
    let ids = [];
    for (const key in this.checkedIdMap) {
      if (this.checkedIdMap[key]) {
        ids.push(key);
      }
    }
    return ids.join(',');
  }

  searchByDept(e) {
    this._cnd['deptId'] = e.node.key;
    this.search();
  }


  //查询角色
  searchRoles(userId) {
    this.httpService.post('system/role/listByUserId', {userId: userId}, (result) => {
      if (result.code !== 0) {
        return;
      }
      this.roles = result.data;
    }, (errorResult) => {
      this.message.error(errorResult.msg);
    });
  }

  roleChange(e) {
    // console.log(e);
    // console.log(this.roles);
  }

  //异步验证 https://blog.csdn.net/u012760435/article/details/86529189
  asyncUniqueValidate(key) {
    return (control: FormControl): any => {
      //进入管道进行串行操作
      //valueChanges表示字段值变更才触发操作
      return control.valueChanges.pipe(
        //同valueChanges，不写也可
        distinctUntilChanged(),
        //防抖时间，单位毫秒
        debounceTime(400),
        //调用服务，参数可写可不写，如果写的话变成如下形式
        //switchMap((val) => this.registerService.isUserNameExist(val))
        switchMap(() => this.isExist(control,key)),
        //对返回值进行处理，null表示正确，对象表示错误
        map(res => res['code'] == 0 ? {duplicate: true} : null),
        //每次验证的结果是唯一的，截断流
        first()
      );
    };
  }

  isExist(control,k) {
    let param = {};
    param[k] = control.value;
    let userId = this.validateForm.value.userId;
    if (userId && userId > 0) {
      param['userId'] = userId;
    }
    return this.httpService.p('system/user/isExist', param);
  }

  //响应式
  resizeWidth;
  @HostListener('window:resize', ['$event'])
  onResize(event) {
    this.resizeWidth = event.target.innerWidth;
    //console.log(this.resizeWidth);
  }

  isSm(){
    if(this.resizeWidth<=800 || Xutils.isMobile()){
      return true;
    }
    return false;
  }

}
